package com.orangelife.mobile.individual.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.curry.android.http.HttpUtil;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.thirdsdk.baidu.MyLocationListener;
import com.orangelife.mobile.common.activity.BaseMapActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.login.activity.SelectCommunityActivity;
import com.orangelife.mobile.login.adapter.SelectCityGridAdapter;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

/**
 * 选择城市
 * 
 * @author yw
 * 
 */
@Deprecated
public class SwitchCityActivity extends BaseMapActivity implements
		OnClickListener {
	/* 选择城市标题 */
	private TextView tvSelectCityTitle;
	/* 表示查找的图片 */
	private ImageView ivSearch;
	/* 查找的输入框 */
	private EditText etSearch;
	/* 城市列表 */
	private GridView gvCity;
	/* 选择城市的自定义适配器 */
	private SelectCityGridAdapter<Map<String, Object>> adapter;
	private TextView tvCity;
	private List<Map<String, Object>> list;
	private Handler handler;
	private Dialog dialog, dialog2;
	public static final int GET_CITY = 1;
	private HashMap<String, Object> map;
	private FrameLayout llCity = null;
	private boolean isFirstLoc = true;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.activity_select_city);
		ExitApplication.getInstance().addActivity(this);
		initView();
		findView();
		// getCurrentCity();
		// registerReceiver();
		// sendRequestForGetCity();
	}

	public void hideInput(View v) {
		InputMethodManager imm = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		// edit.setCursorVisible(false);//失去光标
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	private void setToastNet() {
		if (isConnected()) {
			getCurrentCity();
			registerReceiver();
			sendRequestForGetCity();
		}
	}

	/**
	 * 是否联网
	 * 
	 * @return true-联网，false-断网；
	 */
	@Override
	public boolean isConnected() {
		if (!NetworkUtil.isConnectedNet(SwitchCityActivity.this)) {
			return false;
		}
		return true;
	}

	private void sendRequestForGetCity() {
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", null);
		rootMap.put("url", Constant.PATH_SELECT_CITY);
		rootMap.put("wat", 1);
		new JSONRequest(JSONRequest.GET, rootMap, mHandler, HttpUtil.ACTION_URI);
	}

	private void sendRequestForGetCity2(String search) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("search", search);
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", map);
		rootMap.put("url", Constant.PATH_SELECT_CITY + "?");
		rootMap.put("wat", 1);
		new JSONRequest(JSONRequest.GET, rootMap, mHandler, HttpUtil.ACTION_URI);
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				if (msg.obj != null) {
					list = JsonReponseHandler.getListFromJson(
							String.valueOf(msg.obj), adapter, dialog);
					if (list != null) {
						adapter.setList(list);
						adapter.notifyDataSetChanged();
						if (list.size() == 0) {
							ToastHelper
									.getInstance()
									.displayToastWithQuickClose(
											getResources()
													.getString(
															R.string.no_searsch_city_info));
						}
					}

				} else {
					ToastHelper.getInstance().displayToastWithQuickClose(
							getResources().getString(
									R.string.failed_to_get_auth_info));
				}
				break;
			case 1011:
				isLogin(dialog);
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onResume() {
		if (isFirstLoc && mLocClient != null) {
			mLocClient.start();
		}
		setToastNet();
		super.onResume();
	}

	/**
	 * 定位当前城市
	 */
	private void getCurrentCity() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case Constant.WHAT_ERROR_HTTP:
					ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
					break;
				case GET_CITY:
					dialog2.dismiss();
					if (msg.obj != null) {
						map = (HashMap<String, Object>) JSONHelper
								.jsonToMap(String.valueOf(msg.obj));

						String city = map.get("city").toString().equals("null") ? ""
								: map.get("city").toString();
						tvCity.setText(city);
						if (city.equals("")) {
							/** 判断是否是第一次定位 */
							if (isFirstLoc) {
								isFirstLoc = false;
								ToastHelper
										.getInstance()
										.displayToastWithQuickClose(
												getResources()
														.getString(
																R.string.failed_to_positioning_city));
								if (!isConnected()) {
									openBuilder();
								}
							}

						}
						if (mLocClient != null) {
							mLocClient.stop();
						}
					} else {
						ToastHelper.getInstance().displayToastWithQuickClose(
								getResources().getString(
										R.string.failed_position));
					}
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
	}

	private void initView() {
		tvSelectCityTitle = (TextView) findViewById(R.id.tv_title);
		tvCity = (TextView) findViewById(R.id.tv_city);
		ivSearch = (ImageView) findViewById(R.id.iv_search);
		etSearch = (EditText) findViewById(R.id.et_search_city);
		gvCity = (GridView) findViewById(R.id.gvCities);
//		llCity = (FrameLayout) findViewById(R.id.ll_city);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rlLocateCity:
			Intent intent = new Intent(SwitchCityActivity.this,
					SelectCommunityActivity.class);
			String cityName = tvCity.getText().toString();
			if (!StringUtil.isContainBlank(cityName)) {
				Bundle bundle = new Bundle();
				bundle.putBoolean("isLocation", true);
				CommSp2.setCityName(cityName);
				intent.putExtras(bundle);
				startActivity(intent);
				if (mLocClient != null) {
					mLocClient.stop();
				}
			} else {
				ToastHelper.getInstance().displayToastWithQuickClose(
						getResources().getString(
								R.string.failed_position_choose));
				return;
			}

			break;
		case R.id.iv_search:
			String search = etSearch.getText().toString();
			dialog = DialogHelper.getInstance().createLoadingDialog(SwitchCityActivity.this,
					Constant.LOADING);
			dialog.show();
			sendRequestForGetCity2(search);
			break;
		default:
			break;
		}
	}

	/**
	 * 注册广播接收
	 */
	private void registerReceiver() {
		dialog2 = DialogHelper.getInstance().createLoadingDialog(this, getResources()
				.getString(R.string.positioning_city));
		dialog2.show();
//		receiver = new MapReceiver(handler);
		IntentFilter filter = new IntentFilter();
		filter.addAction("MapService");
		registerReceiver(receiver, filter);
	}

	private void findView() {
		int flag = 1;
		tvSelectCityTitle.setText(getResources()
				.getString(R.string.choose_city));
		list = new ArrayList<Map<String, Object>>();
		adapter = new SelectCityGridAdapter<Map<String, Object>>(this, list);
		gvCity.setAdapter(adapter);
		ivSearch.setOnClickListener(this);
		llCity.setOnClickListener(this);
		gvCity.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(SwitchCityActivity.this,
						SwitchCommunityActivity.class);
				String city = list.get(position).get("city").toString();
				String longitude = list.get(position).get("longitude")
						.toString();
				String latitude = list.get(position).get("latitude").toString();
				intent.putExtra("longitude", longitude);
				intent.putExtra("latitude", latitude);
				intent.putExtra("cityName", city);
				CommSp2.setCityName(city);
				intent.putExtra("isLocation", false);
				startActivity(intent);
				if (mLocClient != null) {
					mLocClient.stop();
				}
				finish();
			}
		});
	}

	// @Override
	// protected void onDestroy() {
	// if (mLocClient != null) {
	// mLocClient.stop();
	// Log.e("location", "停止定位。2");
	// }
	// /* 注销广播接收 */
	// unregisterReceiver(receiver);
	// super.onDestroy();
	// }

	@Override
	public MyLocationListener initListener(MyLocationListener myListener) {
		if (!isConnected()) {
			openBuilder();
			return null;
		}
		myListener = new MyLocationListener(this, null, null);
		return myListener;
	}

	private void openBuilder() {
		new AlertDialog.Builder(SwitchCityActivity.this)
				.setTitle(getResources().getString(R.string.prompt))
				.setMessage(getResources().getString(R.string.net_text_prompt))
				.setPositiveButton(getResources().getString(R.string.sure),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								Intent intent = new Intent();
								intent.setClassName("com.android.settings",
										"com.android.settings.Settings");
								startActivity(intent);
							}
						})
				.setNegativeButton(getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {

							}
						}).show();
	}

}